var countdown=require('../public/javascripts/countdown'),sdc = require('sdc-clients')

var dc_config=require('../config/dc')['poc']
	,vmapi = new sdc.VMAPI(dc_config.vmapi)
module.exports = {
	get:function(req, res) {
		if(req.headers.userid&&req.headers.userid!='null')
			return vmapi.getVm({uuid: req.params.uuid},function(err, vm){
				if (err) {
				console.log(err)
				}else{
					var options = {
						hostname: '192.168.115.239', 
						path: '/jobs?vm_uuid='+vm.uuid+'&offset=0&limit=1',
						method: 'GET',
						headers: {"Accept": "application/json"}
					};
					require('http').request(options, function (resd) {
						var body = '';
						resd.setEncoding('utf8');
						resd.on('data',function(d){
							body += d;
						}).on('end', function(){
							var job=JSON.parse(body)[0]
							if(job.execution==="running"||job.execution==="queued"){
								vm.job=job.task
								vm.jobid=job.uuid
							}
							if(req.query.image){
								var image_uuid=''
								if (vm.brand=== 'kvm') {
									var disks = vm.disks
									if(disks.length && disks[0].image_uuid)image_uuid=disks[0].image_uuid
								}else image_uuid=vm.image_uuid
								req.params.uuid=image_uuid
								require('./images').get(req, res,function(err){
									res.send({vm:vm,image:req.image});
								})
							}
						});
					}).on('error', function(e) {
						
					}).end();
				}
			})
		return res.send({path:'loginView.html'})
	},
	action:function (req, res, next) {
		var actions = {
			start: vmapi.startVm,
			stop: vmapi.stopVm,
			reboot: vmapi.rebootVm,
			delete: vmapi.deleteVm
		};
		var fn = actions[req.params.action];
		var body = {};
		body.creator_uuid = req.headers.userid;
		body.origin = 'adminui';
		body.uuid = req.params.uuid;
		fn.call(vmapi,body,function (err, obj){
			if (err) {
			}
			res.send(obj);
		});
	}
}